import {
	sendAjaxRequest,
	findTargetData,
	copy
} from '../libs/utils.js';
import handleStyleLink from '../libs/handleStyleLink.js'
import handleDataProcess from '../libs/handleDataProcess.js'
export default {
	computed: {
		itemW() {
			return list => {
				var itemW = 0;
				if (list.common.direction === 'vertical') {
					itemW = list.common.width;
				} else {
					if (list.common.wrap || list.type === 'waterfall') {
						itemW = (list.common.width - list.common.xPadding * (list.common.horizontalNum - 1)) / list.common.horizontalNum;
					} else if(list.type !== 'mutiStyleList'){
						itemW = list.common.itemW;
					}
				}
				return itemW;
			}
		},
		itemH() {
			return list => {
				if (list.type !== 'waterfall' && list.type !== 'mutiStyleList') {
					return list.common.itemH;
				}
				return 0
			}
		},
		waterfallLayouts() {
			return (children,waterfall) => {
				var arr = [],arr1 = [];
				children.forEach(child => {
					if (child.type === 'layout') {
						child.common.x = 0;
						child.common.y = 0;
						if(child.cid !== waterfall.common.leftSpaceId){
							arr.push([].concat(child));
						}else{
							arr1.push(child)
						}
					}
				});
				return {arr,arr1};
			}
		},
		listItemH() {
			return (index, list) => {
				var idx = index % list.waterfallLayouts.length;
				return list.waterfallLayouts[idx][0].common.height
			}
		},
		mutiStyleListChild(){
			return children=>{
				var obj = {}
				children.forEach(child => {
					if (child.type === 'layout') {
						child.common.x = 0;
						child.common.y = 0;
						obj[child.cid] = [].concat(child)
					}
				})
				return obj
			}
		}
	},
	methods: {
		listItemStyle(list) {
			var style = '';
			if(list.type !== 'mutiStyleList'){
				style += 'width:' + this.itemW(list) + 'rpx;height:' + this.itemH(list) + 'rpx;';
			}
			if (list.type === 'waterfall') {
				style += 'position:absolute;'
			}else{
				style += 'margin-right:'+list.common.xPadding+'rpx;margin-bottom:'+list.common.yPadding+'rpx;'
			}
			return style
		},
		initList(list, children) {
			if (list.type === 'waterfall') {
				var layouts = this.waterfallLayouts(children, list)
				list.waterfallLayouts = layouts.arr
				list.waterfallLt = layouts.arr1
				// 如果类型是瀑布流,如果瀑布流中的layout个数为0，则不显示
				if (list.waterfallLayouts.length === 0) {
					return
				}
			}
			
			if (list.type === 'mutiStyleList') {
				list.mutiChildren = this.mutiStyleListChild(children)
			}
			
			// 列表数据以静态为优先,如果没有静态数据,则调ajax请求数据
			if (list.staticData && list.staticData.data) {
				var newData = findTargetData(list.staticData.data, list.staticData.bindData || [], 'list') || [];
				// #ifdef H5
				if(this.$editMode){
					newData = copy(newData)
				}
				// #endif
				// 如果是瀑布流,则处理列表数据
				if (list.type === 'waterfall') {
					this.waterfallPoi(newData, list)
				}
				if (list.type === 'mutiStyleList') {
					newData = handleStyleLink(newData, list.staticData.styleLink);
				}
				newData = handleDataProcess(newData, list.staticData.process,'list');
				// 修复修改组件配置项时,静态数据列表样式不刷新的问题
				this.$nextTick(() => {
					list.listArray = newData;
					list.loadmoreShow = false
					list.bindData = list.staticData.bindData || [];
				})
			} else if (list.ajax && list.ajax.length > 0) {
				var ajax = list.ajax[0];
				// 如果需要滚动加载,则先获取到页码和每页个数
				if (list.common.direction === 'horizontal' && !list.common.wrap) {
				} else if (list.common.scrollLoad) {
					var pageField = ajax.data.filter(item => item.key === ajax.pageField);
					if (pageField.length > 0) {
						list.page = pageField[0].val * 1;
						list.opage = list.page;
					}
					var sizeField = ajax.data.filter(item => item.key === ajax.sizeField);
					if (sizeField.length > 0) {
						list.size = sizeField[0].val * 1;
						list.osize = list.size;
					}
				}
				this.sendListAjax(list, ajax);
			}
			// 接收广播,由外部触发,发ajax请求
			var itemEventName = 'sendAjax-' + this.pageConfig.cid + '-' + list.cid;
			uni.$off(itemEventName)
			uni.$on(itemEventName, payload => {
				if (list.ajax && list.ajax.length > 0) {
					this.$set(list,'listArray',[])
					this.$set(list,'bindData',[])
					this.$set(list,'page',list.opage)
					this.$set(list,'size',list.osize)
					this.$set(list,'status','loading')
					this.sendListAjax(list, list.ajax[0], payload.notToLogin);
				}
			})
			uni.$on('tab-list-gap-'+this.pageConfig.cid,()=>{
				if(list.common.scrollLoad){
					this.calcListGap(list)
				}
			})
		},
		//滚动加载
		listOnscrollBot(list) {
			// 当this.pageConfig.active !== false时，说明此页面是父页面，或子页面（已激活）
			if (this.pageConfig.active !== false && list.common.scrollLoad && list.ajax && list.ajax.length > 0 && list.page >= 0 && list.size > 0 && list.status !== 'nomore' && list.status !== 'loading') {
				this.listScrollToBot(list, list.ajax[0])
			}
		},
		listScrollToBot(list, ajax) {
			ajax.data.some(item => {
				if (item.key === ajax.pageField) {
					item.val = ++list.page;
					return true;
				}
			});
			this.sendListAjax(list, ajax);
		},
		// 处理瀑布流的方法
		waterfallPoi(newData, list) {
			if (newData.length === 0) {
				return
			}
			var arr = [], firstRowNum;
			// 如果一开始没有数据得时候
			if (list.listArray.length === 0) {
				// 如果左上角需要留白，则第一个框的位置，先设置一个高度
				if (list.common.leftSpaceH > 0) {
					arr.push({
						left: 0,
						sum: list.common.leftSpaceH
					})
				}
				var leftSpaceLen = arr.length;
				firstRowNum = list.common.horizontalNum - leftSpaceLen;
				if(newData.length < firstRowNum){
					firstRowNum = newData.length
				}
				var nowLeft;
				// 一开始没有数据时，算出第一行得高度
				for (var i = 0; i < firstRowNum; i++) {
					nowLeft = (this.itemW(list) + list.common.xPadding) * (i + leftSpaceLen);
					arr.push({
						left: nowLeft,
						sum: this.listItemH(i, list)
					})
					newData[i].l = nowLeft
					newData[i].t = 0
					newData[i].h = this.listItemH(i, list)
				}
			} else {
				// 如果一开始有数据，是滚动加载出来得数据，则先得出上一行的高度
				// 先从数据中取出倒数两行的个数的数据
				arr = list.listArray.slice(-list.common.horizontalNum * 2).map(item => ({ left: item.l, sum: item.t + item.h }))
				var newArr = []
				for (var i = 0; i < list.common.horizontalNum; i++) {
					var maxI = 0, maxH = arr[0].sum, nowH;
					arr.forEach((obj, index) => {
						if (obj.left !== (this.itemW(list) + list.common.xPadding) * i) {
							return
						}
						nowH = obj.sum
						if (nowH > maxH) {
							maxH = obj.sum
							maxI = index
						}
					})
					newArr.push(arr[maxI])
				}
				arr = newArr	//将末尾多余一行个数的数据去除
				firstRowNum = 0	//从0开始计算数据
			}
			// 如果一开始没有数据，接下来从第二行开始处理；如果是滚动加载得数据，则从新数据得第一个开始计算，firstRowNum=0
			newData.forEach((item, index) => {
				if (index < firstRowNum) {
					return
				}
				var minI = 0, minH = arr[0].sum, nowH;
				arr.forEach((obj, index) => {
					nowH = obj.sum
					if (nowH < minH) {
						minH = obj.sum
						minI = index
					}
				})
				item.l = arr[minI].left
				item.t = arr[minI].sum + list.common.yPadding
				item.h = this.listItemH(index, list)
				arr[minI].sum = item.t + item.h
			})
			// 计算瀑布流组件加载更多显示的位置
			var maxI = 0, maxH = arr[0].sum, nowH;
			arr.forEach((obj, index) => {
				nowH = obj.sum
				if (nowH > maxH) {
					maxH = obj.sum
					maxI = index
				}
			})
			list.maxH = maxH
		},
		calcListH(list) {
			var listHeight = list.common.height;
			if (list.listArray.length === 0) {
				return listHeight
			}
			if (list.type !== 'waterfall') {
				if (list.common.direction === 'vertical') {
					listHeight = this.itemH(list) * list.listArray.length
				} else if (list.common.direction === 'horizontal' && list.common.wrap) {
					var preRow = parseInt(list.listArray.length / list.common.horizontalNum);
					var lastRow = list.listArray.length % list.common.horizontalNum > 0 ? 1 : 0
					var everyH = this.itemH(list) + list.common.yPadding;
					listHeight = (preRow + lastRow) * everyH
				}
			}else{
				listHeight = list.maxH
			}
			return listHeight
		},
		calcListGap(list){
			if(!this.$editMode && list.common.scrollLoad){
				var listHeight = this.calcListH(list)
				var gap = listHeight - list.common.height
				uni.$emit('h-gap-'+this.pageConfig.cid,gap+78)
			}
		},
		// 发ajax的方法
		sendListAjax(list, ajax, notToLogin) {
			list.status = 'loading';
			list.loadmoreShow = true;
			sendAjaxRequest(ajax, this.options, '', this.pageConfig.variable, this.pageConfig.cid, this.pageConfig, notToLogin).then(res => {
				var newData = res.listData || []
				list.bindData = res.bindData;
				// 如果是瀑布流,则处理列表数据
				if (list.type === 'waterfall') {
					this.waterfallPoi(newData, list)
				}
				if (list.type === 'mutiStyleList') {
					newData = handleStyleLink(newData, ajax.styleLink);
				}
				newData = handleDataProcess(newData, ajax.process, 'list');
				if (!this.$editMode && list.common.scrollLoad && list.page >= 0 && list.size > 0) {
					list.listArray = list.listArray.concat(newData);
					if (list.listArray.length >= res.count) {
						list.status = 'nomore';
					} else {
						list.status = 'loadmore';
					}
					list.loadmoreShow = list.listArray.length > 0;
				} else {
					list.listArray = newData;
					list.loadmoreShow = false;
				}
				this.calcListGap(list)
			})
		}
	}
}
